package com.atguigu.gulimall.member.interceptor;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.constant.AuthConstant;
import com.atguigu.common.vo.MemberResVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    private static final ThreadLocal<MemberResVo> cache = new ThreadLocal<>();

    public static MemberResVo getLoginUserInfo() {
        return cache.get();
    }


    private static final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String path = request.getRequestURI();
        boolean match = antPathMatcher.match("/member/**", path);
        if (match) {
            return true;
        }


        // 获取用户属性
        HttpSession session = request.getSession();
        Object val = session.getAttribute(AuthConstant.LOGIN_USER);
        if (val == null) {
            // 用户未登录，，重定向到登录页
            session.setAttribute("msg", "请先进行登录");
            response.sendRedirect(AuthConstant.USER_LOGIN_PAGE_URL);
            return false;
        }
        cache.set(objToBean(val, MemberResVo.class));
        return true;
    }

    private <T> T objToBean(Object obj, Class<T> clazz) {
        String jsonStr = JSON.toJSONString(obj);
        return JSON.parseObject(jsonStr, clazz);
    }
}
